import asyncio
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QLineEdit, QTextEdit, QPushButton, QLabel, 
                            QMessageBox, QScrollArea)
from PyQt5.QtCore import QThread, pyqtSignal, Qt
import configparser
import atexit

import blivedm.monitors.open_live_monitor as openlive
import blivedm.monitors.web_monitor as web
import blivedm.play.roulette as roulette

# TEST_ROOM_IDS = [192, 26427138]
DEFAULT_AUTH_CODE = 'EN2I51220AO07'


class MonitorThread(QThread):
    def __init__(self, monitor:"openlive.open_live_monitor"):
        super().__init__()
        self.monitor = monitor
        self._stop_event = asyncio.Event()
        
    def stop(self):
        self._stop_event.set()  # 设置停止事件
        self.quit()
        self.wait()

    def run(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            async def run_forever():
                task = asyncio.create_task(self.monitor.start_monitoring())
                while not self._stop_event.is_set():
                    await asyncio.sleep(1)  # 定期检查停止事件
                task.cancel()  # 取消监控任务
                try:
                    await task  # 等待任务处理取消
                except asyncio.CancelledError:
                    pass
                print("检测到停止事件")
            
            loop.run_until_complete(run_forever())
        except Exception as e:
            print(f"Thread error: {e}")
        finally:
            loop.run_until_complete(self.monitor.stop_monitoring())
            loop.close()
    

class WheelThread(QThread):
    def __init__(self, wheel):
        super().__init__()
        self.wheel = wheel
        
    def run(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            loop.run_until_complete(self.wheel.run_async())
        finally:
            loop.close()

class MessageConsole(QTextEdit):
    def __init__(self):
        super().__init__()
        self.setReadOnly(True)
    
    def add_message(self, message):
        self.append(message)
        self.verticalScrollBar().setValue(self.verticalScrollBar().maximum())

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_auth()
        self.open_live_monitor = None
        self.init_roulette()
        self.roulette_window = None
        
    def init_auth(self):
        self.auth_window = QWidget()
        layout = QVBoxLayout()
        
        self.auth_label = QLabel("准备连接直播间")
        self.authen_code = QLineEdit()
        self.login_btn = QPushButton("确定")
        
        layout.addWidget(self.auth_label)
        layout.addWidget(QLabel("请输入主播认证码:"))
        layout.addWidget(self.authen_code)
        layout.addWidget(self.login_btn)
        
        self.auth_window.setLayout(layout)
        self.login_btn.clicked.connect(self.check_auth)
        self.setCentralWidget(self.auth_window)
        
    def init_roulette(self):
        # 读取配置文件
        config = configparser.ConfigParser()
        config.read('config.ini')
        
        items = config['PRIZES']['items'].split(',')
        probabilities = [float(prob) for prob in config['PRIZES']['probabilities'].split(',')]
        self.wheel = roulette.LuckyWheel(items,probabilities)

    def check_auth(self):
        print("开始连接")
        self.authen_code = DEFAULT_AUTH_CODE
        self.monitor = openlive.open_live_monitor(self.authen_code)
        self.monitor.message_signal.connect(self.post_message)
        self.monitor_thread = MonitorThread(self.monitor)
        self.monitor_thread.start()
        self.init_ui()

    def open_roulette_window(self):
        # 新增：打开转盘游戏窗口
        self.roulette_thread = WheelThread(self.wheel)
        self.roulette_thread.start()

    def init_ui(self):
        main_widget = QWidget()
        layout = QVBoxLayout()
        
        self.input_box = QLineEdit()
        self.submit_btn = QPushButton("提交")
        # 新增：添加转盘游戏按钮并连接信号和槽
        self.game_btn = QPushButton("玩转盘游戏")
        self.message_console = MessageConsole()
        
        layout.addWidget(QLabel("输入内容:"))
        layout.addWidget(self.input_box)
        layout.addWidget(self.submit_btn)
        layout.addWidget(QLabel("消息记录:"))
        layout.addWidget(self.message_console)
        layout.addWidget(self.game_btn)
        self.game_btn.clicked.connect(self.open_roulette_window)
        
        main_widget.setLayout(layout)
        self.setCentralWidget(main_widget)
        self.submit_btn.clicked.connect(self.process_input)
        
    def process_input(self):
        user_input = self.input_box.text()
        self.message_console.add_message(f"用户输入: {user_input}")
        self.input_box.clear()
        
    def post_message(self, message):
        """供外部调用的消息接口"""
        self.message_console.add_message(message)

    def closeEvent(self, event):
        if self.monitor_thread:
            self.monitor_thread.stop()  # 停止监控线程
            self.monitor_thread.wait()  # 等待线程结束
        super().closeEvent(event)

    # def closeEvent(self, event):
    #     # 停止监控线程
    #     print("stop monitor")
    #     if hasattr(self, 'monitor_thread'):
    #         self.monitor_thread.stop()
        
    #     # 停止转盘线程
    #     print("stop roulette")
    #     if hasattr(self, 'roulette_thread'):
    #         self.roulette_thread.quit()
    #         self.roulette_thread.wait()
        
    #     event.accept()

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.setWindowTitle("连接直播间")
    window.resize(500, 400)
    window.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
            
